// 项目库-我的项目

import React, { useEffect } from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useHistory } from 'react-router';
import { Form, Row, Col, Input, message, Button, Tabs } from 'antd';
import AjaxSelect from '~/components/AjaxSelect';
import { PictureUploader } from '~/components/PictureUploader';
import { FileUploader } from '~/components/FileUploader';
import * as addApi from '~/apis/project/newApi';
import {
  genValidConfig,
  getStageOneInitialValue,
  handleStageOneValue,
  handleStageTwoValue,
  handleStageThreeValue,
  handleStageFourValue,
  handleFormValue,
  getUrlSearch,
  echoFormValue,
  echoStageOneValue,
  echoStageTwoValue,
  echoStageThreeValue,
  echoStageFourValue,
  deleteNullValue,
  guid,
} from './pageConfig';
import { StageOne } from './components/StageOne';
import { StageTwo } from './components/StageTwo';
import { StageThree } from './components/StageThree';
import { StageFour } from './components/StageFour';
import './index.local.sass';

const formItemLayout = {
  wrapperCol: { span: 20 },
};

// 页面渲染
const { TabPane } = Tabs;
const ProjectNew = observer(() => {
  const state = useLocalStore(() => ({
    projectId: getUrlSearch('id') as string,
    loading: false,
    vfData: [] as any,
    faData: [] as any,
    prData: [] as any,
    frData: [] as any,
    mrData: [] as any,
    saData: [] as any,
  }));

  const history = useHistory();
  const [form] = Form.useForm();
  const [formOne] = Form.useForm();
  const [formTwo] = Form.useForm();
  const [formThree] = Form.useForm();
  const [formFour] = Form.useForm();

  // 表单保存
  const onSubmit = () => {
    let project = {} as any;
    let identification = {} as any;
    let procurement = {} as any;
    let implementation = {} as any;
    let transfer = {} as any;

    const { projectId } = state;

    // 基础表单
    project = handleFormValue(form.getFieldsValue());
    if (projectId)project.id = projectId;

    // 阶段1表单
    identification = handleStageOneValue(formOne.getFieldsValue());
    identification.vfm = deleteNullValue(state.vfData);
    identification.faa = deleteNullValue(state.faData);

    // 阶段2表单
    procurement = handleStageTwoValue(formTwo.getFieldsValue());

    // 阶段3表单
    implementation = handleStageThreeValue(formThree.getFieldsValue());
    identification.pcPmr = deleteNullValue(state.prData);
    identification.pcFr = deleteNullValue(state.frData);
    identification.mer = deleteNullValue(state.mrData);
    identification.pppSa = deleteNullValue(state.saData);

    // 阶段4表单
    transfer = handleStageFourValue(formFour.getFieldsValue());

    state.loading = true;
    if (projectId) {
      // 保存项目--编辑
      addApi.editProject({ project, identification, procurement, implementation, transfer, shelveStatus: '0' }).then(() => {
        message.success('success');
        history.push('/project/my');
      }).finally(() => {
        setTimeout(() => {
          state.loading = false;
        }, 2000);
      });
    } else {
      // 保存项目--新增
      addApi.addProject({ project, identification, procurement, implementation, transfer, shelveStatus: '0' }).then(() => {
        message.success('success');
        history.push('/project/my');
      }).finally(() => {
        setTimeout(() => {
          state.loading = false;
        }, 2000);
      });
    }
  };

  // 获取表单数据
  const getFormValues = () => form.validateFields().then((values: any) => {
    const project = handleFormValue(values);
    return project;
  });

  // 获取formone数据
  const getFormOneValues = () => formOne.validateFields().then((values: any) => {
    const ProjectIdentification = handleStageOneValue(values);
    const vfm = deleteNullValue(state.vfData);
    const faa = deleteNullValue(state.faData);
    ProjectIdentification.vfm = vfm;
    ProjectIdentification.faa = faa;
    return ProjectIdentification;
  });

  // 获取formtwo数据
  const getFormTwoValues = () => formTwo.validateFields().then((values: any) => {
    const ProjectProcurement = handleStageTwoValue(values);
    return ProjectProcurement;
  });

  // 获取formthree数据
  const getFormThreeValues = () => formThree.validateFields().then((values: any) => {
    const ProjectImplementation = handleStageThreeValue(values);
    ProjectImplementation.pcPmr = deleteNullValue(state.prData);
    ProjectImplementation.pcFr = deleteNullValue(state.frData);
    ProjectImplementation.mer = deleteNullValue(state.mrData);
    ProjectImplementation.pppSa = deleteNullValue(state.saData);
    return ProjectImplementation;
  });

  // 获取formFour数据
  const getFormFourValues = () => formFour.validateFields().then((values: any) => {
    const ProjectTransfer = handleStageFourValue(values);
    return ProjectTransfer;
  });

  // 表单提交
  const onPost = () => {
    let project = {} as any;
    let identification = {} as any;
    let procurement = {} as any;
    let implementation = {} as any;
    let transfer = {} as any;

    const { projectId } = state;

    // 基础表单
    const promise1 = getFormValues().then((params: any) => {
      if (projectId)params.id = projectId;
      project = params;
    }).catch(() => Promise.reject());

    // 阶段1表单
    const promise2 = getFormOneValues().then((params: any) => {
      if (params.vfm.length === 0 || params.faa.length === 0) { // 表格非空判断
        return Promise.reject();
      }
      identification = params;
      return identification;
    }).catch(() => Promise.reject());

    // 阶段2表单
    const promise3 = getFormTwoValues().then((params: any) => {
      procurement = params;
    }).catch(() => Promise.reject());

    // 阶段3表单
    const promise4 = getFormThreeValues().then((params: any) => {
      implementation = params;
    }).catch(() => Promise.reject());

    // 阶段4表单
    const promise5 = getFormFourValues().then((params: any) => {
      transfer = params;
    }).catch(() => Promise.reject());

    state.loading = true;
    // 新增项目
    Promise.all([promise1, promise2, promise3, promise4, promise5]).then(
      () => {
        // 提交---编辑
        if (projectId) {
          addApi.editProject({ project, identification, procurement, implementation, transfer, shelveStatus: '1' }).then(() => {
            message.success('success');

            history.push('/project/my');
          }).finally(() => {
            setTimeout(() => {
              state.loading = false;
            }, 2000);
          });
        } else {
          // 提交---新增
          addApi.addProject({ project, identification, procurement, implementation, transfer, shelveStatus: '1' }).then(() => {
            message.success('success');

            history.push('/project/my');
          }).finally(() => {
            setTimeout(() => {
              state.loading = false;
            }, 2000);
          });
        }
      },
    ).catch(() => {
      state.loading = false;
      message.error('validation error');
    });
  };

  // 获取阶段1表格数据
  const getStageOneTableData = (vfData: any, faData: any) => {
    state.vfData = vfData;
    state.faData = faData;
  };

  // 获取阶段3表格数据
  const getStageThreeTableData = (prData: any, frData: any, mrData: any, saData: any) => {
    state.prData = prData;
    state.frData = frData;
    state.mrData = mrData;
    state.saData = saData;
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const formValue = echoFormValue(formData.project);
    const form1Value = echoStageOneValue(formData.identification);
    const form2Value = echoStageTwoValue(formData.procurement);
    const form3Value = echoStageThreeValue(formData.implementation);
    const form4Value = echoStageFourValue(formData.transfer);
    // 基础表单-填充
    form.setFieldsValue({
      ...formValue,
    });

    // 阶段1-填充
    formOne.setFieldsValue({
      ...form1Value,
    });

    state.vfData = formData.identification.vfm ? formData.identification.vfm.map((vf: any) => ({ ...vf, hasFile: true, key: guid() })) : [];
    state.faData = formData.identification.faa ? formData.identification.faa.map((fa: any) => ({ ...fa, hasFile: true, key: guid() })) : [];
    // state.vfData = [...formData.identification.vfm];
    // state.faData = [...formData.identification.faa];

    // 阶段2-填充
    formTwo.setFieldsValue({
      ...form2Value,
    });

    // 阶段3-填充
    formThree.setFieldsValue({
      ...form3Value,
    });
    state.prData = formData.implementation.pcPmr ? formData.implementation.pcPmr.map((vf: any) => ({ ...vf, hasFile: true, key: guid() })) : [];
    state.frData = formData.implementation.pcFr ? formData.implementation.pcFr.map((vf: any) => ({ ...vf, hasFile: true, key: guid() })) : [];
    state.mrData = formData.implementation.mer ? formData.implementation.mer.map((vf: any) => ({ ...vf, hasFile: true, key: guid() })) : [];
    state.saData = formData.implementation.pppSa ? formData.implementation.pppSa.map((vf: any) => ({ ...vf, hasFile: true, key: guid() })) : [];

    // 阶段4-填充
    formFour.setFieldsValue({
      ...form4Value,
    });
  };

  // initForm
  const initForm = (id: string) => {
    addApi.getProject(id).then((res) => {
      fillForm(res.data);
    });
  };

  const fileUploadOptions = {
    accept: 'application/zip,application/vnd.rar,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf',
    max: 1,
  };

  useEffect(() => {
    if (state.projectId) {
      initForm(state.projectId);
    }
  }, []);

  const { vfData, faData, prData, frData, mrData, saData } = state;

  const { loading } = state;

  return (
    <div>
      <div className="information-container">
        {/* 基础信息 */}
        <Form form={form} layout="vertical" className="basic_information ant-advanced-search-form">
          <div className="basic">
            <div className="basic-top">
              <h3>Project Key Information</h3>
              {/* <div className='uploads'> */}
              {/*  <Button type="primary" className="w-46 mr-2"> */}
              {/*    <DownloadOutlined />Download template */}
              {/*  </Button> */}
              {/*  <div className="flex-1"><FileUploader {...fileUploadOptions} /></div> */}
              {/* </div> */}
            </div>
            <div className="basic-form">
              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label='Project title'
                    name='projectTitle'
                    rules={genValidConfig('Project title')}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={'Country name'}
                    name='countryId'
                    rules={genValidConfig('Country name')}
                    {...formItemLayout}
                  >
                    <AjaxSelect
                      placeholder="Please select"
                      type="countryList"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label={'Sector'}
                    name='industryId'
                    rules={genValidConfig('Industry')}
                    {...formItemLayout}
                  >
                    <AjaxSelect
                      placeholder="Please select"
                      type="industryList"
                    />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item label={'Procuring agency'}
                    name='procuringAgency'
                    rules={genValidConfig('Procuring agency')}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label={'Contact'}
                    name='projectContact'
                    rules={genValidConfig('Contact')}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label={'Phone'}
                    name='phone'
                    rules={genValidConfig({ required: 'false', selfType: 'phone' })}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item label={'Email'}
                    name='email'
                    rules={genValidConfig({ type: 'email', message: 'email' })}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label={'Planned development year'}
                    name='plannedYear'
                    rules={genValidConfig({ selfType: 'numString', message: 'Planned development year' })}
                    {...formItemLayout}
                  >
                    <Input placeholder="Please input" suffix="year(s)"/>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <div className="file-item">
                    <Form.Item label={'Authorization documents of the government'}
                      name='governmentAuthDoc'
                      rules={genValidConfig({ type: 'array', message: 'Authorization documents of the government' })}
                    >
                      <FileUploader {...fileUploadOptions} />
                    </Form.Item>
                  </div>
                  <p className="text-xs cor-grey">Support ZIP RAR DOC DOCX PDF only</p>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item label={'Images'} name='thumbnail'>
                    <PictureUploader
                      max={1}
                      accept="image/jpeg,image/bmp,image/png"
                    />
                  </Form.Item>
                  <p className="mt-2 text-xs cor-grey">Support JPG JPEG PNG BMP only</p>
                </Col>
              </Row>
            </div>
          </div>
        </Form>

        {/* 阶段信息 */}
        <div className="stage">
          <Tabs defaultActiveKey="1" size='large'>
            <TabPane tab="Preparation stage" key="1">
              <Form form={formOne} layout="vertical" initialValues={getStageOneInitialValue()} className="basic_information ant-advanced-search-form">
                <StageOne getData={getStageOneTableData} tableData={{ vfData, faData }}/>
              </Form>
            </TabPane>

            <TabPane tab="Procurement Stage" key="2" forceRender={true}>
              <Form form={formTwo} layout="vertical" className="basic_information ant-advanced-search-form">
                <StageTwo />
              </Form>
            </TabPane>

            <TabPane tab="Implementation Stage" key="3" forceRender={true}>
              <Form form={formThree} layout="vertical" className="basic_information ant-advanced-search-form">
                <StageThree getData={getStageThreeTableData} tableData={{ prData, frData, mrData, saData }}/>
              </Form>
            </TabPane>

            <TabPane tab="Transfer Stage" key="4" forceRender={true}>
              <Form form={formFour} layout="vertical" className="basic_information ant-advanced-search-form">
                <StageFour />
              </Form>
            </TabPane>
          </Tabs>
        </div>
      </div>
      <div className="btns">
        <Button
          type="primary"
          htmlType="submit"
          style={{ marginRight: 16 }}
          onClick={onSubmit}
          disabled={loading}
        >
          Save & Close
        </Button>
        <Button
          onClick={onPost}
          disabled={loading}
        >Post</Button>
      </div>

    </div>
  );
});

export default ProjectNew;
